#pragma once
#include <iostream>
#include <cstring>
#include <pthread.h>

namespace MutexModule
{
    class Mutex
    {
    public:
        Mutex()
        {
            int n = pthread_mutex_init(&_mutex, nullptr);
            if (n != 0)
            {
                std::cerr << "mutex init failed: " << strerror(n) << std::endl;
            }
        }

        void Lock()
        {
            int n = pthread_mutex_lock(&_mutex);
            if (n != 0)
            {
                std::cerr << "mutex lock failed: " << strerror(n) << std::endl;
            }
        }

        void Unlock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            if (n != 0)
            {
                std::cerr << "mutex unlock failed: " << strerror(n) << std::endl;
            }
        }

        pthread_mutex_t* Get()
        {
            return &_mutex;
        }

        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_mutex);
            if (n != 0)
            {
                std::cerr << "mutex destroy failed: " << strerror(n) << std::endl;
            }
        }

    private:
        pthread_mutex_t _mutex;
    };

    // 采用RAII风格，进行管理
    class LockGuard
    {
    public:
        LockGuard(Mutex& mutex)
            :_mutex(mutex)
        {
            _mutex.Lock();
        }

        ~LockGuard()
        {
            _mutex.Unlock();
        }
    private:
        Mutex& _mutex;
    };
}